package com.assets.Check;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.assets.Adapter.Adper;
import com.assets.BaseActivity;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.bean.Check_adap_bean;
import com.assets.bean.Check_choose_bean;
import com.assets.newNHF.util.LogUtils;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/5/14.
 */

public class Check_choose extends BaseActivity {
    private ListView listView;
    private String url = "http://" + Url.IP + "/api/checkdetailQueryById";
    private Handler handler = new Handler();
    private List<String> check_id = new ArrayList<>();
    private List<Check_adap_bean> check = new ArrayList<>();
    private List<String> CheckdetailId = new ArrayList<>();
    private String checkId;
    private BaseAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int intiLayout() {
        return R.layout.check_choose;
    }

    @Override
    public void initView() {
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        init();
    }

    @Override
    public void initData() {
        load();
    }

    private void load() {
        OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        //divisionId
        String checkStatus = getIntent().getStringExtra("checkStatus");
        String divisionId = "";
        if (checkStatus.equals("2")) {
            divisionId = getIntent().getStringExtra("deptId");
        }
        if (!TextUtils.isEmpty(divisionId)) {
            formBody.add("divisionId", divisionId);
        }
        formBody.add("checkId", checkId)
                .add("userId", Since_case.getInstance().getUserId())
                .add("companyId", Since_case.getInstance().getCompany())
                .add("checkStatus", getIntent().getStringExtra("checkStatus")); //传递键值对参数
        final Request request = new Request.Builder()//创建Request 对象。
                .url(url)
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //回调方法的使用与get异步请求相同
                showToast("请连接网络后重试");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("message","message="+response.message());
//                if (!response.isSuccessful()){
//                    showToast("message="+response+",code="+response.code());
//                    return;
//                }
                final String responseData = response.body().string();

                LogUtils.d(responseData);
                Gson gson = new Gson();
                Log.d("userList===","responseData="+responseData);
                List<Check_choose_bean> userList = gson.fromJson(responseData, new TypeToken<List<Check_choose_bean>>() {
                }.getType());

                for (int i = 0; i < userList.size(); i++) {
                    check.add(new Check_adap_bean(false, userList.get(i).getDept(), userList.get(i).getType(), userList.get(i).getPlannum(), userList.get(i).getResult(), userList.get(i).getDeptId()));
                    check_id.add(userList.get(i).getCheckdetailId());
                }
                adapter = new Adper(check, Check_choose.this);
                handler.post(() -> {
                    listView.setAdapter(adapter);
                });
            }
        });
    }

    private void init() {
        Intent intent = getIntent();
        checkId = intent.getStringExtra("checkId");
        String isEdit = intent.getStringExtra("isEdit");
        ImageView fh = (ImageView) findViewById(R.id.fh);
        TextView tv_title = findViewById(R.id.title_text);
        tv_title.setText("选择使用部门");
        Button button1 = (Button) findViewById(R.id.button1);
        Button button2 = (Button) findViewById(R.id.button2);
        Button button3 = (Button) findViewById(R.id.button3);
        listView = (ListView) findViewById(R.id.listveiw);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            String checkDetailId = "[" + check_id.get(position) + "]";
            String deptId = check.get(position).getDeptId();
            Intent intent1 = new Intent(Check_choose.this, Check.class);
            if (!TextUtils.isEmpty(isEdit)) {
                intent1.putExtra("isEdit", isEdit);
            }
            intent1.putExtra("id", checkId);
            intent1.putExtra("deptId", deptId);
            intent1.putExtra("checkId", checkDetailId.trim().replace(" ", ""));
            startActivity(intent1);
            finish();
           /* Adper.ViewHolder viewHolder = (Adper.ViewHolder) view.getTag();
            viewHolder.checkBox.toggle();
            check.get(position).setIscheck(viewHolder.checkBox.isChecked());
            if (viewHolder.checkBox.isChecked()) {
                CheckdetailId.add(check_id.get(position));
            } else {
                CheckdetailId.remove(check_id.get(position));
            }*/
            // 用TextView显示
        });
        button1.setOnClickListener(v -> {
            int j = 0;
            for (int i = 0; i < check.size(); i++) {
                if (check.get(i).ischeck()) {
                    j++;
                }
            }
            if (j < check.size()) {
                CheckdetailId.clear();
                for (int i = 0; i < check.size(); i++) {
                    // 改变boolean
                    check.get(i).setIscheck(true);
                    // 如果为选中
                    if (check.get(i).ischeck()) {
                        CheckdetailId.add(check_id.get(i));
                    }
                }
                adapter.notifyDataSetChanged();
            } else {
                for (int i = 0; i < check.size(); i++) {
                    // 改变boolean
                    check.get(i).setIscheck(false);
                    // 如果为选中
                    if (!check.get(i).ischeck()) {
                        CheckdetailId.remove(check_id.get(i));
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
        button2.setOnClickListener(v -> {
            CheckdetailId.clear();
            for (int i = 0; i < check.size(); i++) {
                // 改值
                if (check.get(i).ischeck()) {
                    check.get(i).setIscheck(false);
                } else {
                    check.get(i).setIscheck(true);
                }
                // 刷新
                adapter.notifyDataSetChanged();
                // 如果为选中
                if (check.get(i).ischeck()) {
                    CheckdetailId.add(check_id.get(i));
                } else CheckdetailId.remove(check_id.get(i));
            }
        });
        fh.setOnClickListener(v -> finish());
        /*button3.setOnClickListener(v -> {
            Intent intent1 = new Intent(Check_choose.this, Check.class);
            intent1.putExtra("id", checkId);
            intent1.putExtra("checkId", CheckdetailId.toString().trim().replace(" ", ""));
            startActivity(intent1);
            finish();
        });*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
